<?php

namespace App\Http\Controllers\Api;

use App\Model\ShopOrderFstModel;
use App\Model\StoreGoodModel;
use App\Model\StoreModel;
use App\Model\UserModel;
use App\Model\ConfigModel;
use App\Model\NoticeModel;
use App\Model\UserPaytypeModel;
use App\Model\UserWalletModel;
use App\Model\DepositModel;
use Illuminate\Http\Request;
use App\Model\UserModel as User;
use App\Model\UserLoginModel;
use App\Http\Controllers\Controller;
use App\Model\UserWalletModel as UserWallet;
use App\Model\UserWalletLogModel as UserWalletLog;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Cache;
use App\Services\Msfl;


class PersonalController extends Controller
{
	//用户信息
	public function info(){
		$user = User::where('id', request()->uid)->select('user','picname','id','invite_code','phone','email','login_type','is_auth','level')->first();
		if (!$user) {
			return ['code' => 0, 'msg' => retStrInfo(13)];
		}

		//用户是否第三方
		$party = UserLoginModel::where('uid',$user['id'])->first();
		if(empty($user->picname)){
			if(empty($party['picname'])){
				$user->picname = "http://".$_SERVER['HTTP_HOST']."/user.png";
			}else{
				$user->picname = $party['picname'];
			}
		}else{
			$user->picname = "http://".$_SERVER['HTTP_HOST'].$user->picname;
		}

		if($user->login_type == 1){
			$user->username = $user->phone;
		}else{
			$user->username = $user->email;
		}
		$end_time = "";
		$user_store = StoreModel::where('uid',$user['id'])->first();
		if($user_store){
			$end_time = $user_store['end'];
		}
		$user['end_time'] = $end_time;
		return ['code' => 1, 'data' => $user];
	}

	//我的钱包
	public function wallet(){
		$data = [];
		//用户钱包
		$user_wallet = UserWallet::where('uid',request()->uid)->first();
		//现金账户
		$data['money'] = $user_wallet['money'];
		//云仓库货款
		$data['lock_money'] = $user_wallet['lock_money'];
		//日志分类
		$data['type'] = [
			[
				'tid' => 1,
				'tname' => '现金',
				'list' => [
					['id'=>'1','msg'=>'充值'],
					['id'=>'2','msg'=>'提现'],
					['id'=>'3','msg'=>'转货款'],
					['id'=>'4','msg'=>'成为VIP'],
					['id'=>'5','msg'=>'销售奖'],
					['id'=>'6','msg'=>'领导奖'],
					['id'=>'7','msg'=>'教育奖'],
					['id'=>'8','msg'=>'云仓库收益'],
					['id'=>'9','msg'=>'系统操作'],
					['id'=>'15','msg'=>'利益'],
				]
			],
			[
				'tid' => 2,
				'tname'=>'云货款',
				'list' => [
					['id'=>'3','msg'=>'转货款'],
					['id'=>'10','msg'=>'入库'],
					['id'=>'11','msg'=>'下单'],
					['id'=>'12','msg'=>'创客奖'],
					['id'=>'13','msg'=>'退还388'],
				],
			],
		];
		//日志
		$data['log'] = UserWalletLog::where(function ($query) {
			if (request()->type) {
				$query->where('type', request()->type);
			}
			if (request()->status) {
				$query->where('status', request()->status);
			}

		})
			->where('uid',request()->uid)
			->orderBy('id', 'desc')
			->paginate(10);

		if($data['log']){
			foreach($data['log'] as $k=>$v){
				$type = ['1'=>'现金','2'=>'货款','股票'];
				$v['type_name'] = $type[$v['type']];
				$status = ['1'=>'系统','2'=>'提现','3'=>'转货款','4'=>'开通VIP','5'=>'销售奖','6'=>'领导奖','7'=>'教育奖','8'=>'云仓库收益','10'=>'入库','11'=>'购买','12'=>"创客奖",'13'=>'退还388','14'=>'返还VIP押金','15'=>'下单返利','16'=>'拼团下单','17'=>'赠送股票','18'=>'返还本金','19'=>'赠送现金'];
				$v['status_name'] = $status[$v['status']];
			}
		}
		return ['code'=>1,'data'=>$data];
	}

	//更改头像
	public function edit_pic(Request $request)
	{
		//头像
		if ($request->hasFile('file') && $request->file('file')->isValid()) {
			$allow_types = ['png', 'jpeg', 'jpg'];

			if (!in_array($request->file('file')->getClientOriginalExtension(), $allow_types)) {
				return ['code' => 0, 'msg' => retStrInfo(19)];
			}
			$ext = $request->file('file')->getClientOriginalExtension();

			//获取文件的绝对路径
			$path = $request->file('file')->getRealPath();

			//定义文件名
			$filename = date('Ymdhis') . '-' . rand(1000, 9999) . "." . $ext;

			//存储文件。disk里面的public。总的来说，就是调用disk模块里的public配置
			$shangchuan = Storage::disk('headpic')->put($filename, file_get_contents($path));

			if ($shangchuan) {
				$add = User::where('id', request()->uid)->update(['picname' => '/upload/headpic/' . $filename]);
				if (!$add) {
					return ['code' => 0, 'msg' => retStrInfo(20)];
				}
				$picname = "/upload/headpic/" . $filename;
				return ['code' => 1, 'msg' => retStrInfo(21), 'data' => "http://" . $_SERVER['HTTP_HOST'] . $picname];
			} else {
				return ['code' => 0, 'msg' => retStrInfo(22)];
			}
		} else {
			return ['code' => 0, 'msg' => retStrInfo(23)];

		}
	}

	//编辑信息(昵称)
	public function editinfo(){
		if(!request()->user){
			return ['code'=>0,'msg'=>retStrInfo(2)];
		}
		$str_user ='/[\'.,:;*?~`!@#$%^&+=)(<>{}]|5261\]|\[|\/|\\\|\"|\|/';
		if(preg_match($str_user,request()->user)){
			return ['code'=>0,'msg'=>'昵称不可包含特殊字符'];
		}
		$user_len = mb_strlen(request()->user,'UTF8');
		if($user_len > 15){
			return ['code'=>0,'msg'=>"请输入15位以内的昵称"];
		}

		if(User::where('user',request()->user)->first()){
			return ['code'=>0,'msg'=>retStrInfo(3)];
		}
		DB::beginTransaction();
		try {
			$user = User::where('id',request()->uid)->first();
			if(!$user){
				return ['code' => 0, 'msg' => retStrInfo(13),'data'=>$user];
			}
			$auth_name = "/^[\x{4e00}-\x{9fa5}]{2,6}$/u";
			if (preg_match($auth_name, request()->user)) {
				$pin = app('pinyin');
				$pinyin =$pin->abbr(request()->user);
			}else{
				$pinyin = request()->user;
			}
			//首字母
			$head = pinying($pinyin);
			User::Where('id',$user->id)->update(['user' => request()->user,'head'=>$head]);
			DB::commit();
			return ['code' => 1, 'msg' => retStrInfo(24),'data'=>request()->user];
		} catch (Expectation $e) {
			DB::rollback();
			return ['code' => 0, 'msg' => retStrInfo(25)];
		}
	}

	//验证登录密码和支付密码
	public function check_pass(){
		$user = UserModel::Dolist(request()->uid);
		if(!$user || $user['state'] == 2){
			return ['code'=>0,'msg'=>retStrInfo(97)];
		}
		//是否输入密码
		if(!request()->password){
			return ['code'=>0,'msg'=>retStrInfo(9)];
		}
		//是否输入二级密码
		if(!request()->paypass){
			return ['code'=>0,'msg'=>retStrInfo(10)];
		}
		//密码是否正确
		if (!Hash::check(request()->password, $user['password'])) {
			return ['code' => 0, 'msg' => retStrInfo(98)];
		}
		//二级密码是否正确
		if (!Hash::check(request()->paypass, $user['paypass'])) {
			return ['code' => 0, 'msg' => retStrInfo(56)];
		}
		return ['code'=>1,'msg'=>'信息正确'];

	}

	//重新绑定手机号
	public function binduser(){
		//重新绑定,1手机号   2邮箱
		//判断账户/邮箱格式是否正确
		$str_phone = '/^[1]\\d{10}$/';
		$str_email = '/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})$/';

		if(request()->type == 1){
			if (!preg_match($str_phone, request()->username)) {
				return ['code' => 0, 'msg' => retStrInfo(4)];
			}
			$user = User::where('phone', request()->username)->first();

		}else{
			if (!preg_match($str_email, request()->username)) {
				return ['code' => 0, 'msg' => retStrInfo(5)];
			}
			$user = User::where('email', request()->username)->first();
		}

		if($user){
			return ['code' => 0, 'msg' => retStrInfo(6)];
		}

		//验证码
		$str = '/^\\d{6}$/';
		if (!preg_match($str, request()->code)) {
			return ['code' => 0, 'msg' => retStrInfo(7)];
		}
		$code = Cache::get(request()->username);
		if ($code != request()->code) {
			return ['code' => 0, 'msg' => retStrInfo(8)];
		}


		if(request()->type == 1){
			if(User::where('id',request()->uid)->update(['phone'=>request()->username])){
				Cache::pull(request()->username);
				return ['code' => 1, 'msg' => retStrInfo(32)];
			}else{
				return ['code' => 0, 'msg' => retStrInfo(33)];
			}
		}else{
			if(User::where('id',request()->uid)->update(['email'=>request()->username])){
				Cache::pull(request()->username);
				return ['code' => 1, 'msg' => retStrInfo(34)];
			}else{
				return ['code' => 0, 'msg' => retStrInfo(35)];
			}
		}

	}

	//更改密码/二级密码
	public function edit_pass(){

		$user = User::where('id', request()->uid)->first();
		if(!$user){
			return ['code' => 0, 'msg' => retStrInfo(13)];
		}
		if($user->login_type == 1){
			$cache_user = $user->phone;
		}else{
			$cache_user = $user->email;
		}
		if (!request()->password) {
			return ['code' => 0, 'msg' => retStrInfo(36)];
		}
		$str = '/^\\d{6}$/';
		if (!preg_match($str, request()->code)) {
			return ['code' => 0, 'msg' => retStrInfo(7)];
		}
		$code = Cache::get($cache_user);
		if ($code != request()->code) {
			return ['code' => 0, 'msg' => retStrInfo(8),'data'=>$code];
		}
		DB::beginTransaction();
		try {
			if (request()->cut == 2) {
				$str = '/^\\d{6}$/';
				if (!preg_match($str, request()->password)) {
					return ['code' => 0, 'msg' => retStrInfo(10)];
				}
				$user->update([
					'paypass' => Hash::make(request()->password),
				]);
			} else {
				//判断是否包含中文
				$str_pass = '/[\x7f-\xff]/';
				if(preg_match($str_pass,request()->password)){
					return ['code'=>0,'msg'=>"密码不能包含中文字符"];
				}
				if(strlen(request()->password) > 16 || strlen(request()->password) < 6){
					return ['code'=>0,'msg'=>"请输入长度为6~16位的密码"];
				}
				$user->update([
					'password' => Hash::make(request()->password),
				]);
			}
			$data['id'] = $user->id;
			$data['token'] = $user->token;
			Cache::pull($cache_user);
			DB::commit();
			return ['code' => 1, 'msg' => retStrInfo(24),'data'=>$data];
		} catch (Expectation $e) {
			DB::rollBack();
			return ['code' => 0, 'msg' => retStrInfo(25)];
		}
	}

	//转货款
	public function transfer(){

		//用户信息
		$user = User::where('id',request()->uid)->first();

		if($user['is_auth'] != 1){
			return ['code'=>0,'msg'=>retStrInfo(95)];
		}

		//用户钱包资产
		$wallet = UserWallet::where('uid',request()->uid)->first();

		if(!$wallet){
			return ['code'=>0,'msg'=>retStrInfo(54)];
		}
		//转账数量
		if(!request()->num){
			return ['code'=>0,'msg'=>retStrInfo(55)];
		}
		//二级密码是否输入
		if(!request()->paypass){
			return ['code'=>0,'msg'=>retStrInfo(10)];
		}
		//二级密码是否正确
		if (!Hash::check(request()->paypass, $user['paypass'])) {
			return ['code' => 0, 'msg' => retStrInfo(56)];
		}

		//可用现金余额是否充足
		if(request()->num > $wallet->money){
			return ['code'=>0,'msg'=> retStrInfo(57)];
		}
		DB::beginTransaction();
		try {
			//增加扣除日志
			UserWallet::handleAccount(request()->uid,request()->num,'-','转货款',1,3);
			UserWallet::handleAccount(request()->uid,request()->num,'+','转货款',2,3);

			//转货款判断(使用388现金支付成为银卡的用户,累计充1万货款后返388服务费)
			$msfl = new Msfl();
			//增加个人业绩
			$msfl->performance(request()->uid,request()->num);
			$msfl->ten_thoundsand(request()->uid);
		
			DB::commit();
//
		}catch (Expectation $e) {
			DB::rollback();
			return ['code' => 0, 'msg' => retStrInfo(59)];
		}
        return ['code' => 1, 'msg' => retStrInfo(58)];
	}

	//团队
	public function team(){
		$szm = array('A','B','C','D','E','F','G','H','J','K','L','M','N','P','Q','R','S','T','W','X','Y','Z','#');
		$data['szm'] = $szm;//首字母
		//直推下级人数
		$data['user_sum'] = UserModel::where('pid',request()->uid)->count();
		//直推下级信息
		$data['user'] = UserModel::letter(request()->uid,request()->keywords);
		$data['user_cy'] = UserModel::getList(request()->uid,request()->keywords);

		return ['code'=>1,'msg'=>'','data'=>$data];
	}

	//团队搜索
	public function team_search(){
		$data = [];
		if(request()->keywords){
			$user = UserModel::where(function ($query) {
				if (request()->keywords) {
					$query->where('phone', 'like', "%".request()->keywords."%");
					$query->Orwhere('user','like',"%".request()->keywords."%");
					$query->Orwhere('email','like',"%".request()->keywords."%");
				}
			})->where('pid',request()->uid)->get();
			foreach($user as $k=>$v){
				//用户是否第三方
				$party = UserLoginModel::where('uid',$v['id'])->first();
				if(empty($v['picname'])){
					if(empty($party['picname'])){
						$data[$k]['picname'] = "http://".$_SERVER['HTTP_HOST']."/user.png";
					}else{
						$data[$k]['picname'] = $party['picname'];
					}

				}else{
					$data[$k]['picname'] = "http://".$_SERVER['HTTP_HOST'].$v['picname'];
				}

				$data[$k]['user'] = $v['user'];
				//账号
				if($v['login_type'] == 1){
					$data[$k]['username'] = $v['phone'];
				}else{
					$data[$k]['username'] = $v['email'];
				}
				//是否是VIP
				$data[$k]['is_vip'] = $v['is_vip'];
				$data[$k]['id'] = $v['id'];
				$data[$k]['is_auth'] = $v['is_auth'];
				$data[$k]['level'] = $v['level'];
			}
		}
		return ['code'=>1,'data'=>$data];
	}

	//团队详情
	public function team_detail(){
		//判断该账户是否存在
		$user = UserModel::where('id',request()->id)->first();

		if(!$user) {
			return ['code' => 0, 'msg' => retStrInfo(13)];
		}
		$party = UserLoginModel::where('uid',request()->id)->first();
		if(empty($user['picname'])){
			if(empty($party['picname'])){
				$data['picname'] = "http://".$_SERVER['HTTP_HOST']."/user.png";
			}else{
				$data['picname'] = $party['picname'];
			}

		}else{
			$data['picname'] = "http://".$_SERVER['HTTP_HOST'].$user['picname'];
		}
		$data['user'] = $user['user'];
		if($user['nickname']){
			$data['user'] = $user['nickname'];
		}
		$data['is_vip'] = $user['is_vip'];
		$data['is_auth'] = $user['is_auth'];//1是  3否
		$data['level'] = $user['level'];

		//团队人数
		$data['user_team'] = UserModel::where('pid',request()->id)->count();
		//团队货款
		$user_team = UserModel::where('pid',request()->id)->get();
		$data['user_lock_money'] = 0;
		$data['user_store_num'] = 0;
		$data['user_store_profit'] = 0;
		if($user_team){
			foreach($user_team as $k=>$v){
				$data['user_lock_money'] += UserWallet::where('uid',$v['id'])->sum('lock_money');
				//仓库
				$store = StoreModel::where('uid',$v['id'])->where('state',1)->first();
				if($store){
					$user_store = StoreGoodModel::where('sid',$store['id'])->get();
					foreach($user_store as $i=> $j){
						$data['user_store_num'] += $j['gsell_price']*$j['num'];
					}
				}

				$user_store_sids = StoreGoodModel::where('sid',$store['id'])->get();
				$sids = '';
				foreach ($user_store_sids as $k=>$v){
					$sids .= $v['id'].',';
				}
				$sids = explode(',',trim($sids,','));
				$user_store_slist = ShopOrderFstModel::whereIn('sid',$sids)->get();
				$profit_ratio = ConfigModel::getValue('profit');
//				//仓库商品
//				$store_good = ShopOrderFstModel::where('sid',$store['id'])->select('cost_price','sell_price','num')->get();
				foreach($user_store_slist as $key=>$val){
					$data['user_store_profit'] += bcmul($val['sell_price']*$profit_ratio,$val['num'],2);
				}
			}
		}
		$data['user_store_profit'] = ceil($data['user_store_profit']);
		return ['code'=>1,'data'=>$data];
	}

	//消息未读数量
	public function info_num(){
		//未读消息数量
		$list['read_no'] = NoticeModel::where('type',2)->where('uid',request()->uid)->where('is_read',2)->count();
		return ['code'=>1,'msg'=>'返回信息','data'=>$list];
	}

	//消息列表
	public function infomation(){
		//用户消息列表
		$data['list'] = NoticeModel::where('type',2)->where('uid',request()->uid)->select('id','title','content','created_at')->get();
		NoticeModel::where('uid',request()->uid)->where('is_read',2)->where('type',2)->update(['is_read'=>1]);
		return ['code'=>1,'msg'=>'返回数据','data'=>$data];
	}


	//提现方式
	public function dep_type(){
		$data = [];
		$data['list'] = [];
		$types = UserPaytypeModel::where('uid',request()->uid)->get();
		foreach($types as $k=>$v){
			$data['list'][$k]['id'] = $v['id'];
			$data['list'][$k]['bank'] = $v['bank'];
			$data['list'][$k]['logo'] = "http://".$_SERVER['HTTP_HOST'].$v['bank_logo'];
		}
		return ['code'=>1,'msg'=>'返回数据','data'=>$data];
	}
	//提现
	public function deposit(){
		if(!request()->tid){
			return ['code'=>0,'msg'=>retStrInfo(103)];
		}
		if(!request()->num){
			return ['code'=>0,'msg'=>retStrInfo(104)];
		}
		if(!request()->paypass){
			return ['code'=>0,'msg'=>retStrInfo(10)];
		}
		DB::beginTransaction();
		try{
			$info = UserModel::where('id',request()->uid)->first();
			//二级密码是否正确
			if (!Hash::check(request()->paypass, $info['paypass'])) {
				return ['code' => 0, 'msg' => retStrInfo(56)];
			}
			//用户钱包
			$user = UserWalletModel::where('uid',request()->uid)->first();
			if($user['money'] < request()->num){
				return ['code'=>0,'msg'=>retStrInfo(105)];
			}
			//提现方式信息
			$paytype = UserPaytypeModel::where('id',request()->tid)->first();
			if(!$paytype){
				return ['code'=>0,'msg'=>retStrInfo(106)];
			}
			//增加提现日志
			$dis = DepositModel::create([
				'uid' => request()->uid,
				'num' => request()->num,
				'num_befor' => $user->money,
				'num_after' => $user->money - request()->num,
				'name' => $paytype['name'],
				'account' => $paytype['account'],
				'bank' => $paytype['bank'],
				'bank_name' => $paytype['bank_name'],
				'type' => $paytype['type'],
			]);

			//增加扣除日志
			UserWallet::handleAccount(request()->uid,request()->num,'-','现金提现',1,2,'deposit',$dis->id);
			DB::commit();
			return ['code'=>1,'msg'=>retStrInfo(108)];
		}catch(Exception $e){
			DB::rollBack();
			return ['code'=>1,'msg'=>retStrInfo(109)];
		}
	}

	//我的股票
	public function shares(){
		$uid = request()->uid;
		//用户的钱包
		$wallet = UserWallet::where('uid',$uid)->first();
		if(!$wallet){
			return ['code'=>0,'msg'=>'用户资产异常'];
		}
		//我的股票
		$data['shares'] = $wallet['shares'];
		//股票日志
		$aa = [];
		$log = UserWalletLog::where('uid',$uid)->where('type',3)->orderBy('id','desc')->paginate(15);
		foreach($log as $k=>$v){
			$aa[$k]['msg'] = $v['msg'];
			$aa[$k]['num'] = number_format($v['num'],0);
			$aa[$k]['created_at'] = date('Y-m-d H:i:s',$v->created_at->timestamp);
		}
		$data['log'] = $aa;
		return ['code'=>1,'msg'=>'返回数据','data'=>$data];
	}
	//设置备注
	public function remark(){
		$id = request()->id;
		$user = UserModel::where('id',$id)->first();
		if(!$user){
			return ['code'=>0,'msg'=>'该团队成员不存在'];
		}
		if(request()->nickname){
			$str_user ='/[\'.,:;*?~`!@#$%^&+=)(<>{}]|5261\]|\[|\/|\\\|\"|\|/';
				if(preg_match($str_user,request()->nickname)){
					return ['code'=>0,'msg'=>'备注名不可包含特殊字符'];
				}
				$user_len = mb_strlen(request()->nickname,'UTF8');
				if($user_len > 10){
					return ['code'=>0,'msg'=>"请输入10位以内的备注名"];
				}
				$nickname = request()->nickname;
		}else{
			$nickname = $user['user'];
		}
		$auth_name = "/^[\x{4e00}-\x{9fa5}]{2,6}$/u";
		if (preg_match($auth_name, $nickname)) {
			$pin = app('pinyin');
			$pinyin =$pin->abbr($nickname);
		}else{
			$pinyin = $nickname;
		}
		//首字母
		$head = pinying($pinyin);
		DB::beginTransaction();
		try{
			UserModel::where('id',$id)->update(['nickname'=>request()->nickname,'head'=>$head]);
			DB::commit();
		}catch(Exception $e){
			DB::rollBack();
			return ['code'=>0,'msg'=>'设置失败'];
		}
		return ['code'=>1,'msg'=>'设置成功'];
	}
}
